package com.yc.blog.web;

import biz.BizException;
import com.yc.blog.dao.UserDao;
import com.yc.blog.entity.User;
import com.yc.blog.util.Utils;
import com.yc.blog.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping({"user"})
public class UserDo {

    @Autowired
    UserDao userDao;

    @RequestMapping("login")
    Mono<Result> login(User user, ServerWebExchange exchange) {
        return Mono.just(user)
                .doOnNext(u -> {
                    Utils.chcekEmpty(user.getName(), "请输入用户名!");
                    Utils.chcekEmpty(user.getPwd(), "请输入密码!");
                })
                .flatMap(u -> {
                    // MD5加密
                    user.setPwd(DigestUtils.md5DigestAsHex((user.getName() + user.getPwd()).getBytes()));
                    // 定义查询条件
                    ExampleMatcher matcher = ExampleMatcher.matching();
                    matcher = matcher.withMatcher("name", ExampleMatcher.GenericPropertyMatchers.exact());
                    matcher = matcher.withMatcher("pwd", ExampleMatcher.GenericPropertyMatchers.exact());
                    Example<User> example = Example.of(user, matcher);
                    // 执行查询
                    return userDao.findOne(example);
                })
                .switchIfEmpty(Mono.error(new BizException("用户名或密码错误!")))
                .flatMap(u -> {
                    // 清空密码
                    u.setPwd(null);
                    // 获取会话对象
                    return exchange.getSession()
                            .doOnNext(s -> s.getAttributes().put("I", u));
                })
                .map(s -> Result.ok("登录成功!", s.getAttribute("I")));
    }

    @RequestMapping("myinfo")
    Mono<Result> myinfo(@SessionAttribute(required = false) User I) {
        return Mono.just(I == null ?
                Result.err("未登录!") :
                Result.ok("已登录!", I));
    }

}
